package com.wanmait.computershop.webController;

import com.wanmait.computershop.dao.CartDAO;
import com.wanmait.computershop.dao.ProductDAO;
import com.wanmait.computershop.vo.Cart;
import com.wanmait.computershop.vo.Product;
import com.wanmait.computershop.vo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("web")
public class WebCartController {

    @GetMapping("addCartProduct")
    @ResponseBody
    public void addCartProduct(Product product,Integer addNum,HttpSession session)
    {
        User loginUser = (User)session.getAttribute("loginUser");
        Cart cart = CartDAO.isAdded(loginUser.getId(),product.getId());
        if (cart != null)
        {
            CartDAO.updateNumById(cart.getId(),cart.getNum()+addNum);
        }
        else
        {
            Product detailProduct = ProductDAO.selectById(product.getId());
            CartDAO.insertByUidAndProduct(loginUser.getId(),detailProduct,addNum);
        }
    }

    @GetMapping("cartProductNum")
    @ResponseBody
    public String cartProductNum(HttpSession session)
    {
        User loginUser = (User)session.getAttribute("loginUser");
        return CartDAO.countByUid(loginUser.getId()).toString();
    }

    @GetMapping("cart")
    public String cart(Product product, Model model, HttpSession session){
        User loginUser = (User)session.getAttribute("loginUser");
        model.addAttribute("cartList",CartDAO.selectAll(loginUser.getId()));
        return "web/cart";
    }

    @GetMapping("updateCartNum")
    @ResponseBody
    public void updateNum (Integer id, Integer num)
    {
        CartDAO.updateNumById(id,num);
    }

    @GetMapping("delCart")
    @ResponseBody
    public String delCart(Integer cid,HttpSession session)
    {
        User loginUser = (User)session.getAttribute("loginUser");
        CartDAO.delectCartById(cid);
        return CartDAO.countByUid(loginUser.getId()).toString();
    }
}
